<template>

    <HeaderSearch></HeaderSearch>

    <div class="menu_bg">
        <div class="menu">
            <ul class="menu_r">
                <li><a @click.prevent="Index">首页</a></li>

                <li v-for="category1 in category1List">
                    <a @click.prevent="toCategory(category1.id)">{{ category1.name }}</a>
                </li>
            </ul>
            <div class="m_ad">中秋送好礼！</div>
        </div>
    </div>


    <div class="i_bg">
        <div class="postion">
            <span class="fl"></span>
        </div>
        <div class="content">

            <div id="tsShopContainer">
                <div id="tsImgS"><a href="#" title="Images" class="MagicZoom" id="MagicZoom"><img
                            :src="url + product.fileName" width="390" height="390" /></a></div>

            </div>

            <div class="pro_des">
                <div class="des_name">
                    <p>{{ product.name }}</p>
                    {{ product.description }}
                </div>
                <div class="des_price">
                    本店价格：<b>￥{{ product.price}}</b><br />

                    <!-- 库存：{{ product.stock }} -->

                </div>
                <div class="des_share">
                    <div><a href="#" @click.prevent="toCollect()">
                            <img src="/images/heart_h.png" v-if="isCollect == 1" />
                            <img src="/images/heart.png" v-if="isCollect == 0" />
                            收藏商品
                        </a></div>

                </div>

                <div class="des_join">
                    <div class="j_nums"><!-- 商品数量 -->
                        <input type="text" v-model="product.quantity" name="quantity" class="n_ipt" @change="updateQuantity()" />
                        <input type="button" value="" @click="addUpdate();" class="n_btn_1" />
                        <input type="button" value="" @click="jianUpdate();" class="n_btn_2" />
                    </div>
                    <span class="fl"><a href="#" @click.prevent="toPayCar()"><img
                                src="/images/j_car.png" /></a></span><!-- 加入购物车 -->
                </div>
                <br>
                <br>
                 <button @click="goBack">返回</button>
            </div>


            <div class="s_brand">
                <div class="s_brand_img"><img src="/images/sbrand.jpg" width="188" height="132" /></div>
                <div class="s_brand_c">进入品牌专区</div>
            </div>
           
        </div>
    </div>
</template>



<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import store from '@/store'
import HeaderSearch from '@/components/HeaderSearch.vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter();
const route = useRoute();
const url = 'http://192.168.12.159:83/';

const userId = sessionStorage.getItem("id");

const numPatten = /^[1-9][0-9]*$/;
const productId = route.query.id;
const product = ref({});
const category1List = ref({});
const isCollect = ref(0)
const likeProList = ref({})


const Index = () => {
    router.push({ path: '/' })
}

//得到商品数据
const getProducet = async () => {
    try {
        const response = await axios.get('/api/selectById?id=' + productId);
        product.value = response.data.product;
        product.value.quantity = 1;

    } catch (error) {
        console.error('获取数据失败:', error)
    }
}

//收藏夹
const getLikeProduct = async () => {
    if(userId == null){
        return;
    }
    const response = await axios.post('/api/selectCollectProduct', {
        userId: userId,
    })
    likeProList.value = response.data.likeProductList

    if(likeProList.value==null){
        return;
    }
    
    for (let newProduct of likeProList.value) {
        if (newProduct.id == productId) {        
            isCollect.value = 1
        }
    }
    
}
//得到一级分类
const getCategory = async () => {
    try {
        const response = await axios.get('/api/selectCategory1');
        category1List.value = response.data.pc1List;

    } catch (error) {
        console.error('获取数据失败:', error)
    }
}

const toCategory = (id) => {
  router.push({ path: '/searchProduct', query: { id: id } })
}
//添加数量
function addUpdate() {
    product.value.quantity++;
}
//减少数量
function jianUpdate() {
    if (product.value.quantity - 1 < 1) {
        return;
    }
    product.value.quantity--;
}

const updateQuantity = async () => { 
    if(!numPatten.test(product.value.quantity)){
        product.value.quantity = 1;
    }
}

//收藏商品
const addCollectProduct = async () => {
    const request = await axios.post('/api/addCollectProduct', {
        userId: userId,
        productId: product.value.id

    })
}

//取消收藏
const returnCollectProduct = async () => {
    
    const request = await axios.post('/api/returnCollectProduct', {
            userId: userId,
            productId: product.value.id
    })
}

//点击收藏商品
function toCollect() {
    if (userId == null) {
        alert("请先登录！")
        return;
    }

    //收藏
    if (isCollect.value == 0) {
        if (!confirm("是否要收藏【" + product.value.name + "】,最多收藏6个商品")) {
            return;
        }
        isCollect.value = 1;
        addCollectProduct()
    } else {//取消收藏
        if (!confirm("是否要取消收藏【" + product.value.name + "】")) {
            return;
        }
        isCollect.value = 0;
        returnCollectProduct()
    }
}




    //加入购物车
    const toPayCar = async ()=>{
        if(userId == null){
            alert("请先登录！")
            return;
        }
        const userType = sessionStorage.getItem("type");
        if(userType == 1){
            alert("管理员不能加入购物车！")
            return;
        }

        if(!confirm("是否要将【"+product.value.name+"】加入购物车")){
            return;
        }

        
        try{
            const request = await axios.post('/api/addPayCar',{
                userId: userId,
                productId: product.value.id,
                quantity: product.value.quantity,
            })
            alert(request.data.reason)

             // 触发购物车更新事件
            window.dispatchEvent(new CustomEvent('cart-updated'));

        }catch(error){
            console.error('添加失败:', error)
        }
    }

    const goBack = () => {
        router.go(-1)
    }


// 进入管理页面时隐藏HeaderView
onMounted(() => {
    store.commit('setShowPage', 1)
    getProducet();
    getCategory();
    getLikeProduct();
})

// 离开管理页面时恢复HeaderView
onUnmounted(() => {
    store.commit('setShowPage', 0)
})
</script>

<style scoped></style>